<template>
  <div class="course-selection-container">
    <h1 class="page-title">选课管理</h1>
    
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 选课列表 -->
      <el-tab-pane label="选课列表" name="courseList">
        <div class="filter-container">
          <el-form :inline="true" :model="filterForm" class="filter-form">
            <el-form-item label="课程名称">
              <el-input v-model="filterForm.courseName" placeholder="请输入课程名称" clearable />
            </el-form-item>
            <el-form-item label="所属模块">
              <el-select v-model="filterForm.moduleType" placeholder="请选择模块" clearable popper-class="module-select">
                <el-option 
                  v-for="item in moduleOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="课程类型">
              <el-select v-model="filterForm.courseType" placeholder="请选择类型" clearable popper-class="course-type-select">
                <el-option 
                  v-for="item in courseTypeOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleFilter">查询</el-button>
              <el-button @click="resetFilter">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <el-table :data="filteredCourses" style="width: 100%" border v-loading="loading">
          <el-table-column prop="courseCode" label="课程代码" width="120" />
          <el-table-column prop="courseName" label="课程名称" width="200" />
          <el-table-column prop="credits" label="学分" width="80" />
          <el-table-column prop="courseType" label="课程类型" width="120" />
          <el-table-column prop="moduleType" label="所属模块" width="120" />
          <el-table-column prop="teacher" label="任课教师" width="120" />
          <el-table-column prop="timeLocation" label="上课时间地点" width="180" />
          <el-table-column prop="capacity" label="容量" width="80">
            <template #default="scope">
              {{ scope.row.selectedCount }}/{{ scope.row.capacity }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                :disabled="scope.row.isSelected || scope.row.selectedCount >= scope.row.capacity"
                @click="handleSelectCourse(scope.row)"
              >
                {{ scope.row.isSelected ? '已选' : '选课' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCourses"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
      
      <!-- 已选课表 -->
      <el-tab-pane label="已选课表" name="selectedCourses">
        <div class="schedule-container">
          <div class="schedule-header">
            <div class="schedule-title">2023-2024学年 第一学期</div>
            <el-button type="primary" @click="printSchedule">打印课表</el-button>
          </div>
          
          <el-table :data="weekdays" style="width: 100%" border>
            <el-table-column prop="time" label="时间/星期" width="100" />
            <el-table-column prop="monday" label="星期一" />
            <el-table-column prop="tuesday" label="星期二" />
            <el-table-column prop="wednesday" label="星期三" />
            <el-table-column prop="thursday" label="星期四" />
            <el-table-column prop="friday" label="星期五" />
            <el-table-column prop="saturday" label="星期六" />
            <el-table-column prop="sunday" label="星期日" />
          </el-table>
          
          <div class="selected-courses-list">
            <h3>已选课程列表</h3>
            <el-table :data="selectedCourses" style="width: 100%" border>
              <el-table-column prop="courseCode" label="课程代码" width="120" />
              <el-table-column prop="courseName" label="课程名称" width="200" />
              <el-table-column prop="credits" label="学分" width="80" />
              <el-table-column prop="courseType" label="课程类型" width="120" />
              <el-table-column prop="teacher" label="任课教师" width="120" />
              <el-table-column prop="timeLocation" label="上课时间地点" />
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button 
                    type="danger" 
                    size="small" 
                    :disabled="scope.row.courseType === '必修'"
                    @click="handleDropCourse(scope.row)"
                  >
                    退课
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>
      
      <!-- 选课记录 -->
      <el-tab-pane label="选课记录" name="selectionRecords">
        <div class="records-container">
          <el-table :data="selectionRecords" style="width: 100%" border>
            <el-table-column prop="timestamp" label="操作时间" width="180" />
            <el-table-column prop="courseCode" label="课程代码" width="120" />
            <el-table-column prop="courseName" label="课程名称" width="200" />
            <el-table-column prop="operation" label="操作类型" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.operation === '选课' ? 'success' : 'danger'">
                  {{ scope.row.operation }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === '成功' ? 'success' : 'danger'">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 选课确认对话框 -->
    <el-dialog v-model="selectDialogVisible" title="选课确认" width="30%">
      <p>您确定要选择以下课程吗？</p>
      <div class="course-info" v-if="currentCourse">
        <p><strong>课程名称：</strong>{{ currentCourse.courseName }}</p>
        <p><strong>课程代码：</strong>{{ currentCourse.courseCode }}</p>
        <p><strong>学分：</strong>{{ currentCourse.credits }}</p>
        <p><strong>任课教师：</strong>{{ currentCourse.teacher }}</p>
        <p><strong>上课时间地点：</strong>{{ currentCourse.timeLocation }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="selectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectCourse">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 退课确认对话框 -->
    <el-dialog v-model="dropDialogVisible" title="退课确认" width="30%">
      <p>您确定要退选以下课程吗？</p>
      <div class="course-info" v-if="currentCourse">
        <p><strong>课程名称：</strong>{{ currentCourse.courseName }}</p>
        <p><strong>课程代码：</strong>{{ currentCourse.courseCode }}</p>
        <p><strong>学分：</strong>{{ currentCourse.credits }}</p>
        <p><strong>任课教师：</strong>{{ currentCourse.teacher }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dropDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDropCourse">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { studentApi, commonApi } from '@/api'

// 当前激活的标签页
const activeTab = ref('courseList')

// 加载状态
const loading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const totalCourses = ref(0)

// 筛选表单
const filterForm = ref({
  courseName: '',
  moduleType: '',
  courseType: ''
})

// 模块选项
const moduleOptions = ref([])

// 课程类型选项
const courseTypeOptions = ref([])

// 课程列表数据
const courseList = ref([])

// 已选课程
const selectedCourses = ref([])

// 选课记录
const selectionRecords = ref([])

// 当前操作的课程
const currentCourse = ref(null)

// 对话框可见性
const selectDialogVisible = ref(false)
const dropDialogVisible = ref(false)

// 课表数据
const weekdays = ref([])

// 筛选后的课程列表
const filteredCourses = computed(() => {
  let filtered = [...courseList.value]
  
  if (filterForm.value.courseName) {
    filtered = filtered.filter(course => 
      course.courseName.toLowerCase().includes(filterForm.value.courseName.toLowerCase())
    )
  }
  
  if (filterForm.value.moduleType) {
    filtered = filtered.filter(course => course.moduleType === filterForm.value.moduleType)
  }
  
  if (filterForm.value.courseType) {
    filtered = filtered.filter(course => course.courseType === filterForm.value.courseType)
  }
  
  return filtered
})

// 初始化数据
onMounted(async () => {
  await Promise.all([
    fetchDictData(),
    fetchCourseList(),
    fetchSelectedCourses(),
    fetchSelectionRecords(),
    fetchSchedule()
  ])
})

// 获取字典数据
const fetchDictData = async () => {
  try {
    // 获取模块类型
    const moduleRes = await commonApi.getDictData('module_type')
    if (moduleRes.code === 200 && moduleRes.data) {
      moduleOptions.value = moduleRes.data
    }
    
    // 获取课程类型
    const courseTypeRes = await commonApi.getDictData('course_type')
    if (courseTypeRes.code === 200 && courseTypeRes.data) {
      courseTypeOptions.value = courseTypeRes.data
    }
  } catch (error) {
    console.error('获取字典数据失败:', error)
  }
}

// 获取课程列表
const fetchCourseList = async () => {
  loading.value = true
  try {
    const res = await studentApi.getCourseSelection({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      courseName: filterForm.value.courseName,
      moduleType: filterForm.value.moduleType,
      courseType: filterForm.value.courseType
    })
    
    if (res.code === 200 && res.data) {
      courseList.value = res.data.list || []
      totalCourses.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  } finally {
    loading.value = false
  }
}

// 获取已选课程
const fetchSelectedCourses = async () => {
  try {
    const res = await studentApi.getSelectedCourses()
    if (res.code === 200 && res.data) {
      selectedCourses.value = res.data
    }
  } catch (error) {
    console.error('获取已选课程失败:', error)
    ElMessage.error('获取已选课程失败')
  }
}

// 获取选课记录
const fetchSelectionRecords = async () => {
  try {
    const res = await studentApi.getSelectionRecords()
    if (res.code === 200 && res.data) {
      selectionRecords.value = res.data
    }
  } catch (error) {
    console.error('获取选课记录失败:', error)
    ElMessage.error('获取选课记录失败')
  }
}

// 获取课表
const fetchSchedule = async () => {
  try {
    const res = await studentApi.getSchedule()
    if (res.code === 200 && res.data) {
      weekdays.value = res.data
    }
  } catch (error) {
    console.error('获取课表失败:', error)
    ElMessage.error('获取课表失败')
  }
}

// 处理选课
const handleSelectCourse = (course) => {
  currentCourse.value = course
  selectDialogVisible.value = true
}

// 确认选课
const confirmSelectCourse = async () => {
  if (!currentCourse.value) return
  
  try {
    const res = await studentApi.selectCourse(currentCourse.value.id)
    if (res.code === 200) {
      ElMessage.success('选课成功')
      selectDialogVisible.value = false
      
      // 更新课程状态
      const index = courseList.value.findIndex(item => item.id === currentCourse.value.id)
      if (index !== -1) {
        courseList.value[index].isSelected = true
        courseList.value[index].selectedCount++
      }
      
      // 刷新已选课程和课表
      fetchSelectedCourses()
      fetchSchedule()
      fetchSelectionRecords()
    }
  } catch (error) {
    console.error('选课失败:', error)
    ElMessage.error('选课失败')
  }
}

// 处理退课
const handleDropCourse = (course) => {
  currentCourse.value = course
  dropDialogVisible.value = true
}

// 确认退课
const confirmDropCourse = async () => {
  if (!currentCourse.value) return
  
  try {
    const res = await studentApi.dropCourse(currentCourse.value.id)
    if (res.code === 200) {
      ElMessage.success('退课成功')
      dropDialogVisible.value = false
      
      // 更新已选课程列表
      selectedCourses.value = selectedCourses.value.filter(item => item.id !== currentCourse.value.id)
      
      // 更新课程列表状态
      const index = courseList.value.findIndex(item => item.id === currentCourse.value.id)
      if (index !== -1) {
        courseList.value[index].isSelected = false
        courseList.value[index].selectedCount--
      }
      
      // 刷新课表和选课记录
      fetchSchedule()
      fetchSelectionRecords()
    }
  } catch (error) {
    console.error('退课失败:', error)
    ElMessage.error('退课失败')
  }
}

// 处理筛选
const handleFilter = () => {
  currentPage.value = 1
  fetchCourseList()
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.value = {
    courseName: '',
    moduleType: '',
    courseType: ''
  }
  currentPage.value = 1
  fetchCourseList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchCourseList()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchCourseList()
}

// 打印课表
const printSchedule = () => {
  window.print()
}
</script>

<style lang="scss" scoped>
.course-selection-container {
  padding: 20px;
  
  .page-title {
    margin-bottom: 20px;
    font-size: 24px;
    font-weight: bold;
    color: #303133;
  }
  
  .filter-container {
    margin-bottom: 20px;
    
    .filter-form {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      align-items: flex-start;
      
      :deep(.el-form-item) {
        margin-right: 0;
        margin-bottom: 10px;
        min-width: 200px;
        flex: 1;
      }
      
      :deep(.el-form-item:last-child) {
        flex: 0 0 auto;
      }
      
      :deep(.el-select) {
        width: 100%;
      }
      
      :deep(.el-input) {
        width: 100%;
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .schedule-container {
    .schedule-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      .schedule-title {
        font-size: 18px;
        font-weight: bold;
      }
    }
    
    .selected-courses-list {
      margin-top: 30px;
      
      h3 {
        margin-bottom: 15px;
        font-size: 16px;
        font-weight: bold;
      }
    }
  }
  
  .records-container {
    margin-top: 10px;
  }
  
  .course-info {
    background-color: #f5f7fa;
    padding: 15px;
    border-radius: 4px;
    margin: 15px 0;
    
    p {
      margin: 5px 0;
    }
  }
}

// 打印样式
@media print {
  .el-tabs__header,
  .schedule-header button,
  .selected-courses-list {
    display: none !important;
  }
  
  .schedule-container {
    padding: 20px;
    
    .schedule-title {
      font-size: 20px;
      text-align: center;
      margin-bottom: 20px;
    }
  }
}
</style> 